package ln.fxspringarchetype.typehandler;

import ln.fxspringarchetype.model.Student;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GenderTypeHandler implements TypeHandler<Student.Gender> {
    @Override
    public void setParameter(PreparedStatement ps, int i, Student.Gender gender, JdbcType jdbcType) throws SQLException {
        ps.setString(i, gender.getValue());
    }

    @Override
    public Student.Gender getResult(ResultSet rs, String columnName) throws SQLException {
        return parseString(rs.getString(columnName));
    }

    @Override
    public Student.Gender getResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseString(rs.getString(columnIndex));
    }

    @Override
    public Student.Gender getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseString(cs.getString(columnIndex));
    }

    /**
     * 从值转换到枚举值的方法
     * 不要误用valueOf!那是把"MALE"转换成Gender.MALE的!
     *
     * @param genderString
     * @return
     */
    private Student.Gender parseString(String genderString) {
        for (Student.Gender gen : Student.Gender.values()) {
            if (genderString.equals(gen.getValue())) {
                return gen;
            }
        }
        return null;
    }
}
